#include "Game.h"

#include "SceneFactory.h"

#define GAME_SAVENAME	   "game.sav"

std::string Game::_savePath;
GlobalData Game::_globalData;
SaveData Game::_saveData;
ValueMap Game::_strings;

bool Game::initialize()
{
	_savePath = FileUtils::getInstance()->getWritablePath();
	_savePath.append(GAME_SAVENAME);
	loadData();
	_strings = FileUtils::getInstance()->getValueMapFromFile("strings.plist");
	Director::getInstance()->runWithScene(SceneFactory::createMainMenu());
	return true;
}

void Game::exit()
{
	saveData();
	Director::getInstance()->end();
}

bool Game::loadData()
{
	auto fp = fopen(_savePath.c_str(), "rb");
	if (fp == nullptr) {
		return false;
	}
	auto bytes = fread(&_saveData, 1, sizeof(SaveData), fp);
	fclose(fp);
	if (bytes != sizeof(SaveData)) {
		return false;
	}
	return true;
}

bool Game::saveData()
{
	auto fp = fopen(_savePath.c_str(), "wb");
	if (fp == nullptr) {
		return false;
	}
	auto bytes = fwrite(&_saveData, 1, sizeof(SaveData), fp);
	fclose(fp);
	if (bytes != sizeof(SaveData)) {
		return false;
	}
	return true;
}

GlobalData& Game::getGloabalData()
{
	return _globalData;
}

SaveData& Game::getSaveData()
{
	return _saveData;
}

std::string Game::queryString(const std::string& key)
{
	auto it = _strings.find(key);
	if (it == _strings.end()) {
		return std::string();
	}
	return it->second.asString();
}
